package com.jianbo.proxy.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
import java.util.zip.GZIPInputStream;

public class CommonUtil {
	
	/**
	 * 默认缓存大小 8192
	 */
	public static final int DEFAULT_BUFFER_SIZE = 2 << 12;
	
    /**
	 * 生成32位大写UUID序号
	 * @return
	 */
	public static String newUUID() {
		return UUID.randomUUID().toString().replaceAll("-", "").trim().toUpperCase();
	}

	/**
	 * Gzip解压处理
	 *
	 * @param in     Gzip数据
	 * @param length 估算长度，如果无法确定请传入{@link #DEFAULT_BYTE_ARRAY_LENGTH}
	 * @return 解压后的数据
	 * @throws UtilException IO异常
	 * @since 4.1.18
	 */
	public static byte[] unGzip(InputStream in, int length) throws RuntimeException {
		GZIPInputStream gzi = null;
		ByteArrayOutputStream bos;
		try {
			gzi = (in instanceof GZIPInputStream) ? (GZIPInputStream) in : new GZIPInputStream(in);
			bos = new ByteArrayOutputStream(length);
			IoUtil.copy(gzi, bos);
		} catch (IOException e) {
			throw new RuntimeException(e);
		} finally {
			IoUtil.closeIo(gzi);
		}
		// 返回必须在关闭gos后进行，因为关闭时会自动执行finish()方法，保证数据全部写出
		return bos.toByteArray();
	}

	public static byte[] unzip(byte[] respnose) {
		ByteArrayInputStream is = new ByteArrayInputStream(respnose);
		return unGzip(is, DEFAULT_BUFFER_SIZE);
	}

}
